<?php

namespace app\admin\controller;

use app\model\BizModel;
use app\model\BizTagModel;
use app\model\BizTagRelationModel;
use support\Request;
use support\Response;
use Exception;
use app\model\Util;

class BizController
{
    /**
     * 获取商家列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $search = $request->get('search', ''); // 搜索关键词
            $tagIds = $request->get('tag_ids', ''); // 标签ID数组，逗号分隔
            $multiBizId = $request->get('multi_biz_id', ''); // 总店ID

            $query = BizModel::query()
                ->select('*') // 确保查询所有字段包括service
                ->orderBy('sort_by', 'desc')
                ->orderBy('id', 'desc');

            if(!empty($multiBizId)){
                $query->where('multi_biz_id', '=', $multiBizId);
            }
            
            // 如果有搜索关键词，添加搜索条件
            if (!empty($search)) {
                $query->where(function($q) use ($search) {
                    $q->where('name', 'like', '%' . $search . '%')
                      ->orWhere('uscc', 'like', '%' . $search . '%')
                      ->orWhere('biz_phone', 'like', '%' . $search . '%');
                });
            }
            
            // 如果有标签筛选条件，添加标签搜索
            if (!empty($tagIds)) {
                $tagIdArray = explode(',', $tagIds);
                $tagIdArray = array_filter($tagIdArray); // 过滤空值
                
                if (!empty($tagIdArray)) {
                    $query->whereExists(function($subQuery) use ($tagIdArray) {
                        $prefix = get_table_prefix();
                        $subQuery->select(\support\Db::raw(1))
                                ->from('biz_tag_relation')
                                ->whereRaw(table_with_prefix('biz_tag_relation') . '.biz_id = ' . table_with_prefix('biz') . '.id')
                                ->whereIn('biz_tag_relation.tag_id', $tagIdArray);
                    });
                }
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['avatar'] = Util::pathToUrl($item->avatar);
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                // 确保service字段被包含在返回数据中
                $item['service'] = empty($item->service) ? [] : explode('@', $item->service);

                $item['normal_discount'] = round($item->normal_discount,2);
                $item['goods_price_discount'] = round($item->goods_price_discount,2);
                $item['vip_discount'] = round($item->vip_discount,2);
                
                // 计算营业时间
                $item['business_hours'] = $this->formatBusinessHours($item->opentime, $item->close_time);
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 提交/创建商家
     * @param Request $request
     * @return Response
     */
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();

            // 地址和店铺电话不能为空
            if (empty($data['name'])) {
                throw new Exception('名称不能为空');
            }

            if (empty($data['uscc'])) {
                throw new Exception('统一信用代码号不能为空');
            }

            // 地址和店铺电话不能为空
            if (empty($data['shop_address'])) {
                throw new Exception('店铺地址不能为空');
            }

            if (empty($data['biz_phone'])) {
                throw new Exception('店铺电话不能为空');
            }

            // 检查商家名称不能重复（排除自己）
            $nameQuery = BizModel::where('name', $data['name']);
            if (!empty($data['id'])) {
                $nameQuery->where('id', '!=', $data['id']);
            }
            if ($nameQuery->count() > 0) {
                throw new Exception('商家名称已存在');
            }

            // 检查统一信用代码号不能重复（排除自己）
            $usccQuery = BizModel::where('uscc', $data['uscc']);
            if (!empty($data['id'])) {
                $usccQuery->where('id', '!=', $data['id']);
            }
            if ($usccQuery->count() > 0) {
                throw new Exception('统一信用代码号已存在');
            }

            $data['multi_biz_id'] = empty($data['multi_biz_id']) ? 0 : $data['multi_biz_id'];


            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $biz = BizModel::find($data['id']);
                if (!$biz) {
                    throw new Exception('商家不存在');
                }
            } else {
                $biz = new BizModel();
            }

            $biz->fill($data);
            $biz->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $biz->created_at = time();
            }
            
            if (!$biz->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $biz,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除商家
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $biz = BizModel::find($id);
            if (!$biz) {
                throw new Exception('商家不存在');
            }

            if (!$biz->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取所有商家数据
     * @param Request $request
     * @return Response
     */
    public function all(Request $request): Response
    {
        $list = BizModel::where('status','=',1)->whereNull('deleted_at')->get();
        return json([
            'data' => $list,
            'msg' => '获取成功',
            'code' => 20000
        ]);
    }

    /**
     * 更新特别说明
     * @param Request $request
     * @return Response
     */
    public function updateSpecialNote(Request $request): Response
    {
        try {
            $id = $request->post('id');
            $special_note = $request->post('special_note');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $biz = BizModel::find($id);
            if (!$biz) {
                throw new Exception('商家不存在');
            }

            $biz->special_note = $special_note;
            $biz->updated_at = time();
            
            if (!$biz->save()) {
                throw new Exception('更新失败');
            }

            return json([
                'data' => $biz,
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商家已关联的标签
     * @param Request $request
     * @return Response
     */
    public function getBizTags(Request $request): Response
    {
        try {
            $bizId = (int) $request->get('biz_id');
            
            if (empty($bizId)) {
                throw new Exception('商家ID不能为空');
            }

            // 检查商家是否存在
            $biz = BizModel::find($bizId);
            if (!$biz) {
                throw new Exception('商家不存在');
            }

            // 获取商家已关联的标签
            $tagIds = BizTagRelationModel::where('biz_id', $bizId)
                ->pluck('tag_id')
                ->toArray();

            $tags = [];
            if (!empty($tagIds)) {
                $tags = BizTagModel::whereIn('id', $tagIds)
                    ->select('id', 'name', 'description')
                    ->get()
                    ->toArray();
            }

            return json([
                'data' => $tags,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 为商家添加标签
     * @param Request $request
     * @return Response
     */
    public function addBizTag(Request $request): Response
    {
        try {
            $bizId = (int) $request->post('biz_id');
            $tagId = (int) $request->post('tag_id');
            
            if (empty($bizId)) {
                throw new Exception('商家ID不能为空');
            }
            
            if (empty($tagId)) {
                throw new Exception('标签ID不能为空');
            }

            // 检查商家是否存在
            $biz = BizModel::find($bizId);
            if (!$biz) {
                throw new Exception('商家不存在');
            }

            // 检查标签是否存在
            $tag = BizTagModel::find($tagId);
            if (!$tag) {
                throw new Exception('标签不存在');
            }

            // 检查是否已经关联
            $exists = BizTagRelationModel::where('biz_id', $bizId)
                ->where('tag_id', $tagId)
                ->exists();
            
            if ($exists) {
                throw new Exception('该标签已关联到此商家');
            }

            // 创建关联关系
            $relation = new BizTagRelationModel();
            $relation->biz_id = $bizId;
            $relation->tag_id = $tagId;
            $relation->created_at = time();
            $relation->updated_at = time();
            
            if (!$relation->save()) {
                throw new Exception('添加标签失败');
            }

            return json([
                'data' => $relation->toArray(),
                'msg' => '添加标签成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除商家标签关联
     * @param Request $request
     * @return Response
     */
    public function removeBizTag(Request $request): Response
    {
        try {
            $bizId = (int) $request->post('biz_id');
            $tagId = (int) $request->post('tag_id');
            
            if (empty($bizId)) {
                throw new Exception('商家ID不能为空');
            }
            
            if (empty($tagId)) {
                throw new Exception('标签ID不能为空');
            }

            // 查找关联关系
            $relation = BizTagRelationModel::where('biz_id', $bizId)
                ->where('tag_id', $tagId)
                ->first();
            
            if (!$relation) {
                throw new Exception('标签关联关系不存在');
            }

            // 删除关联关系
            if (!$relation->delete()) {
                throw new Exception('删除标签失败');
            }

            return json([
                'data' => null,
                'msg' => '删除标签成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 格式化营业时间
     * @param int|null $opentime 开门时间
     * @param int|null $closeTime 关门时间
     * @return string
     */
    private function formatBusinessHours(?int $opentime, ?int $closeTime): string
    {
        if ($opentime === null || $closeTime === null || $opentime === 0 || $closeTime === 0) {
            return '未设置';
        }
        
        $openHour = sprintf('%02d:00', $opentime);
        $closeHour = sprintf('%02d:00', $closeTime);
        
        return $openHour . ' - ' . $closeHour;
    }
}
